from django.http import JsonResponse
from .exception_enum import StatusCodeEnum
from .response import R
import  logging
from .commonException import BusinessException, APIException, ValidationException
logger = logging.getLogger(__name__)


class ExceptionMiddleware:
    def __init__(self, get_response):
        self.get_response = get_response

    def __call__(self, request):
        response = self.get_response(request)
        return response

    def process_exception(self, request, exception):

        logger.error(f"捕获到异常: {exception}",)

        if isinstance(exception, BusinessException):
            return JsonResponse(
                R.from_enum(exception.enum_cls),
                status=400
            )
        elif isinstance(exception, APIException):
            return JsonResponse(
                R.from_enum(exception.enum_cls),
                status=400
            )
        else:
            return JsonResponse(
                R.error(str(exception), StatusCodeEnum.SERVER_ERR.code),
                status=500
            )
